import { defineStore } from 'pinia';
import utilTip from '@/utils/util.tip';
import type { SettingConfig } from '@/types';
import defaultAvatar from '@/assets/images/avatar-default';
import { localStorageGet, localStorageSet } from '@/utils/util.localStorage';

export const useSettingStore = defineStore('setting', () => {
	// 设置配置
	const settingConfig = ref<SettingConfig>({
		avatar: '',
		cloudSyncUrl: '',
		safePassword: '',
	});

	// 云端同步 URL
	const cloudSyncUrl = computed<string>(() => {
		if (settingConfig.value.cloudSyncUrl[settingConfig.value.cloudSyncUrl.length - 1] === '/') {
			return settingConfig.value.cloudSyncUrl.slice(0, -1);
		}
		return settingConfig.value.cloudSyncUrl;
	});

	// 保存设置
	const handleSaveSetting = (): void => {
		localStorageSet('setting-config', JSON.stringify(settingConfig.value));
		utilTip.success('保存成功');
	};

	onBeforeMount(() => {
		// 获取本地存储的设置
		const localSettingConfig = localStorageGet('setting-config');
		if (localSettingConfig) {
			settingConfig.value = JSON.parse(localSettingConfig);

			if (settingConfig.value.avatar.trim().length < 1) {
				settingConfig.value.avatar = defaultAvatar; // 设置默认头像
			}
			return;
		}

		settingConfig.value.avatar = defaultAvatar; // 设置默认头像
	});

	return {
		cloudSyncUrl,
		settingConfig,
		handleSaveSetting,
	};
});
